<template>
  <div class="layout">
    <div class="main-box">
      <div class="tit">库存管理</div>
      <div class="selector-box">
        <el-form :model="searchInfo" label-position="top">
          <div class="flex-container">
            <el-form-item label="物料名称">
              <div class="input-wrapper">
                <el-input
                  v-model="searchInfo.productName"
                  placeholder="请输入物料名称"
                  clearable
                  @input="handleSearch"
                  style="width: 200px"
                >
                  <template #prefix>
                    <el-icon><search /></el-icon>
                  </template>
                </el-input>
              </div>
            </el-form-item>

            <el-form-item label="物料牌号/款式">
              <div class="input-wrapper">
                <el-input
                  v-model="searchInfo.brandOrStyle"
                  placeholder="请输入物料牌号/款式"
                  clearable
                  @input="handleSearch"
                  style="width: 200px"
                >
                  <template #prefix>
                    <el-icon><search /></el-icon>
                  </template>
                </el-input>
              </div>
            </el-form-item>

            <el-form-item label="物料规格型号">
              <div class="input-wrapper">
                <el-input
                  v-model="searchInfo.specification"
                  placeholder="请输入物料规格型号"
                  clearable
                  @input="handleSearch"
                  style="width: 200px"
                >
                  <template #prefix>
                    <el-icon><search /></el-icon>
                  </template>
                </el-input>
                <el-button
                  type="primary"
                  icon="search"
                  @click="handleSearch"
                  style="height: 100%"
                  >查询</el-button
                >
              </div>
            </el-form-item>

            <el-form-item label="筛选值">
              <div class="input-wrapper">
                <el-select
                  v-model="filterValue"
                  placeholder="选择筛选值"
                  style="width: 200px"
                  @change="handleFilter"
                >
                  <el-option label="原料" value="原料" />
                  <el-option label="成品" value="成品" />
                  <el-option label="其他" value="其他" />
                  <el-option label="只计件" value="只计件" />
                  <el-option label="只计重" value="只计重" />
                  <el-option label="同时计件计重" value="同时计件计重" />
                </el-select>
                <el-button
                  type="primary"
                  icon="filter"
                  @click="handleFilter"
                  style="width: 80px"
                  >筛选</el-button
                >
                <el-button
                  icon="refresh"
                  @click="handleReset"
                  style="width: 80px"
                  >重置</el-button
                >
              </div>
            </el-form-item>
          </div>
        </el-form>
      </div>
      <div class="btn-list">
        <div class="left-btns">
          <el-button icon="clock" text @click="openDialog('dailyDetail')"
            >操作明细</el-button
          >
          <el-button icon="data-analysis" text @click="handleCount"
            >库存统计</el-button
          >
          <el-button icon="document" text @click="handleSnapshot">
            查看快照
          </el-button>
          <el-button icon="document" text @click="handleBackup">
            备份数据
          </el-button>
          <el-button icon="refresh" text @click="handleRefresh">
            刷新
          </el-button>
        </div>
      </div>

      <div class="table-box">
        <el-table
          ref="singleTableRef"
          :data="tableData"
          style="width: 100%; height: 100%"
          border
          @selection-change="handleSelectionChange"
          class="custom-table"
        >
          <el-table-column
            type="index"
            width="55"
            label="编号"
            align="center"
            fixed
          />
          <el-table-column
            prop="productName"
            label="物料名称"
            width="140"
            align="center"
            fixed
          />
          <el-table-column
            prop="specification"
            label="规格型号"
            width="150"
            align="center"
          />
          <el-table-column
            prop="brandOrStyle"
            label="牌号/款式"
            width="110"
            align="center"
          />
          <el-table-column
            prop="internalBrand"
            label="内部牌号"
            width="110"
            align="center"
          />
          <el-table-column
            prop="stock"
            label="当前重量(kg)"
            width="90"
            align="center"
          >
            <template #default="{ row }">
              {{ (Number(row.stock) || 0).toFixed(2) }}
            </template>
          </el-table-column>
          <el-table-column
            prop="usableStock"
            label="可用重量(kg)"
            width="90"
            align="center"
          >
            <template #default="{ row }">
              {{ (Number(row.usableStock) || 0).toFixed(2) }}
            </template> </el-table-column
          ><el-table-column
            prop="piece"
            label="当前数量(pcs)"
            width="90"
            align="center"
          >
            <template #default="{ row }">
              {{ row.piece }}
            </template>
          </el-table-column>
          <el-table-column
            prop="usablePiece"
            label="可用数量(pcs)"
            width="90"
            align="center"
          >
            <template #default="{ row }">
              {{ row.usablePiece }}
            </template>
          </el-table-column>
          <el-table-column
            prop="description"
            label="备注"
            width="150"
            align="center"
          />
          <el-table-column
            prop="operation"
            label="操作"
            width="80"
            fixed="right"
            align="center"
          >
            <template #default="{ row }">
              <el-button
                type="primary"
                icon="Edit"
                plain
                size="small"
                @click="handleEdit(row)"
                >编辑</el-button
              >
            </template>
          </el-table-column>
          <el-table-column
            prop="inbound"
            label="入库/出库"
            width="100"
            fixed="right"
            align="center"
          >
            <template #default="{ row }">
              <el-button
                type="success"
                icon="Checked"
                plain
                size="small"
                :disabled="!hasApprovalRequests(row)"
                @click="handleBound(row)"
                >确认</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="pagination-box">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          v-model:current-page="pageNum"
          :page-sizes="[10, 30, 50, 80, 100]"
          v-model:page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          prev-text="上一页"
          next-text="下一页"
        >
        </el-pagination>
      </div>
    </div>
    <Edit
      :dialogVisible="dialogEditVisible"
      :editData="editData"
      @update:dialogVisible="dialogEditVisible = $event"
    />
    <Snapshot
      :dialogVisible="dialogSnapshotVisible"
      :snapshotData="snapshotData"
      @update:dialogVisible="dialogSnapshotVisible = $event"
    />
    <DailyDetail
      :dialogVisible="dialogDailyDetailVisible"
      @update:dialogVisible="dialogDailyDetailVisible = $event"
    />
    <Approval
      :dialogVisible="dialogApprovalVisible"
      :approvalOrders="filteredApprovalOrders"
      :materialInfo="selectedMaterial"
      :username="username"
      @update:dialogVisible="dialogApprovalVisible = $event"
      @approval-update="handleApprovalUpdate"
    />
    <Statistic
      :dialogVisible="statisticsDialog"
      @update:dialogVisible="statisticsDialog = $event"
    />
  </div>
</template>

<script lang="ts">
import {
  defineComponent,
  reactive,
  toRefs,
  computed,
  ref,
  onMounted,
  watch,
} from "vue";
import Snapshot from "./components/Snapshot.vue";
import DailyDetail from "./components/DailyDetail.vue";
import Approval from "./components/Approval.vue";
import Edit from "./components/Edit.vue";
import Statistic from "./components/Statistic.vue";
import { ElMessage } from "element-plus";
import axios from "axios";
import request from "@/utils/request";
import { useRoute } from "vue-router";

export default defineComponent({
  components: {
    Snapshot,
    DailyDetail,
    Approval,
    Edit,
    Statistic,
  },
  setup() {
    const route = useRoute(); // 获取路由实例

    // 获取路由参数中的 username
    const username = ref((route.params.username as string) || "未知用户");
    console.log(username.value);

    const state = reactive({
      loading: false,
      pageNum: 1, //当前页号
      pageSize: 30,
      tableData: [],
      fullData: [],
      approvalOrders: [],
      filteredApprovalOrders: [] as any[], // 新增过滤后的审批请求
      snapshotData: [],
      currentRow: null,
      dialogEditVisible: false,
      dialogDailyDetailVisible: false,
      dialogApprovalVisible: false,
      statisticsDialog: false, // 统计弹窗状态
      dialogSnapshotVisible: false,
      editData: null,
      formQuery: null,
      filterValue: "",
      selectedMaterial: null as any, //选中物料信息
      //username: username.value,
    });

    // console.log(state.userName);

    const searchInfo = ref({
      productName: "",
      brandOrStyle: "",
      specification: "",
    });

    // 搜索处理函数
    const handleSearch = async () => {
      console.log("搜索内容", searchInfo.value);
      // 判断是否所有输入都为空
      const isAllEmpty = Object.values(searchInfo.value).every(
        (val) => !val || val.trim() === ""
      );
      console.log(isAllEmpty);
      if (isAllEmpty) {
        getList(); // 所有输入为空时重新加载所有数据
        return;
      }

      try {
        // 在此处理搜索逻辑
        let data = JSON.stringify(searchInfo.value);
        const response = await request({
          method: "post",
          url: "inventory/products/getProductsByPrams",
          headers: {
            "Content-Type": "application/json",
          },
          data: data,
        });
        state.fullData = response.data.data;
        updateTableData();
      } catch (error) {
        console.error("获取库存数据失败:", error);
      }
    };

    // 筛选处理函数
    const handleFilter = async () => {
      console.log("筛选内容", state.filterValue);
      // 定义请求参数和接口路径
      let requestData = null;
      let apiPath = "";

      // 处理单位筛选 (pcs/kg)
      if (["只计件", "只计重", "同时计件计重"].includes(state.filterValue)) {
        const quantityMap = { 只计件: 0, 同时计件计重: 1, 只计重: 2 };
        requestData = quantityMap[state.filterValue]; // 直接传数字，无需属性名
        apiPath = "getProductsByIqb";

        // 处理类型筛选 (原料/成品/其他)
      } else if (["原料", "成品", "其他"].includes(state.filterValue)) {
        const typeMap = { 原料: 1, 其他: 3, 成品: 2 };
        requestData = typeMap[state.filterValue];
        apiPath = "getProductsByType";

        // 处理无效筛选值
      } else {
        console.error("无效筛选值:", state.filterValue);
        return;
      }
      console.log(requestData);
      // 在此处理筛选逻辑
      try {
        const response = await request({
          method: "post",
          url: "/inventory/products/" + apiPath,
          data: requestData,
          headers: {
            "Content-Type": "application/json",
          },
        });
        state.fullData = response.data.data;
        updateTableData();
      } catch (error) {
        console.error("获取库存数据失败:", error);
      }
    };

    const selectedRows = ref([]); // 存储选中的行数据

    const handleSelectionChange = (selection: any[]) => {
      selectedRows.value = selection; // 记录选中的行
      console.log("选中的行数据：", selectedRows.value);
    };

    const getBoundRequest = async () => {
      try {
        const response = await request({
          method: "get",
          url: "/inventory/approvement/getAllApprovements",
          headers: { "Content-Type": "application/json" },
        });
        //console.log(response.data);
        if (response.data.success) {
          state.approvalOrders = response.data.data;
          console.log(state.approvalOrders);
        }
      } catch (error) {
        console.log(error);
      }
    };

    const hasApprovalRequests = (row: any) => {
      return state.approvalOrders.some(
        (order) =>
          order.productId === row.id && order.approvementStatus === "未审批"
      );
    };

    const handleBound = (row: any) => {
      if (!row) {
        ElMessage.warning("请选择需要审批的库存项");
        return;
      }
      state.selectedMaterial = { ...row }; // 存储当前物料信息
      // 筛选匹配的审批请求
      state.filteredApprovalOrders = state.approvalOrders.filter(
        (order) =>
          order.productId === row.id && order.approvementStatus === "未审批"
      );

      if (state.filteredApprovalOrders.length === 0) {
        ElMessage.warning("当前商品暂无待确认请求");
        return;
      }
      // 传递匹配的请求并打开审批弹窗
      state.dialogApprovalVisible = true;
    };

    const handleRefresh = async () => {
      await getList();
      ElMessage.success("数据已刷新");
    };

    const handleReset = async () => {
      await getList();
      state.filterValue = null;
    };

    const handleEdit = (row: any) => {
      if (!row) {
        ElMessage.warning("请选择需要编辑的库存项");
        return;
      }
      state.editData = { ...row }; // 将当前选中的库存项数据传递给 Edit 组件
      //console.log("传递给 Edit 组件的数据:", state.editData);
      state.dialogEditVisible = true;
    };

    const handleCount = () => {
      state.statisticsDialog = true;
    };

    const handleSnapshot = async () => {
      // 获取快照
      state.dialogSnapshotVisible = true;
      try {
        const response = await request({
          method: "get",
          url: "inventory/products/backup/latest",
          headers: { "Content-Type": "application/json" },
        });
        state.snapshotData = JSON.parse(response.data.data);
      } catch (error) {
        console.log(error);
      }
    };

    const handleBackup = async () => {
      try {
        const response = await request({
          method: "post",
          url: "inventory/backup/manual",
          headers: {
            "Content-Type": "application/json",
          },
        });
        ElMessage(response.data.data);
      } catch (error) {
        console.error("备份库存数据失败:", error);
      }
    };
    const handleApprovalUpdate = (updatedOrder: any) => {
      // 更新审批列表
      const index = state.approvalOrders.findIndex(
        (o) => o.requestId === updatedOrder.requestId
      );
      if (index > -1) {
        state.approvalOrders.splice(index, 1, updatedOrder);
      }
      getList();
    };

    const openDialog = (dialogType: string) => {
      //console.log(`打开对话框：${dialogType}`);
      state.dialogDailyDetailVisible = false;
      state.dialogApprovalVisible = false;

      if (dialogType === "dailyDetail") {
        state.dialogDailyDetailVisible = true;
        //console.log('每日明细弹窗打开:', state.dialogDailyDetailVisible);
      } else if (dialogType === "approval") {
        state.dialogApprovalVisible = true;
        //console.log('审批弹窗打开:', state.dialogApprovalVisible);
      }
    };

    // 更新当前页显示的数据
    const updateTableData = () => {
      const start = (state.pageNum - 1) * state.pageSize;
      const end = start + state.pageSize;
      state.tableData = state.fullData.slice(start, end);
    };

    // 计算表项总数
    const total = computed(() => state.fullData.length);

    const getList = async () => {
      try {
        const response = await request({
          method: "get",
          url: "/inventory/products/getAllProducts",
          headers: {
            "Content-Type": "application/json",
          },
        });
        // 获取审批请求数据
        await getBoundRequest();
        // 添加排序逻辑
        state.fullData = response.data.data
          .map((product) => ({
            ...product,
            // 添加排序权重字段，存在审批请求的排前面
            hasRequest: state.approvalOrders.some(
              (order) =>
                order.productId === product.id &&
                order.approvementStatus === "未审批"
            )
              ? 1
              : 0,
          }))
          .sort((a, b) => {
            // 先按是否有请求排序（1在前）
            if (b.hasRequest !== a.hasRequest)
              return b.hasRequest - a.hasRequest;
            // 其次按最后更新时间排序
            return (
              new Date(b.updatedAt).getTime() - new Date(a.updatedAt).getTime()
            );
          });
        //console.log(response.data.data);
        updateTableData();
        return Promise.resolve();
      } catch (error) {
        console.error("获取库存数据失败:", error);
        return Promise.reject(error);
      }
    };

    const handleSizeChange = (pageSize: number) => {
      state.pageSize = pageSize;
      updateTableData(); // 更新当前页显示的数据
    };

    // 实现分页
    const handleCurrentChange = (pageNum: number) => {
      state.pageNum = pageNum;
      updateTableData(); // 更新当前页显示的数据
    };

    onMounted(async () => {
      await getBoundRequest();
      await getList();
    });

    watch(
      () => state.approvalOrders,
      () => {
        // 当审批请求变化时重新排序
        state.fullData = state.fullData
          .map((product) => ({
            ...product,
            hasRequest: state.approvalOrders.some(
              (order) => order.productId === product.id
            )
              ? 1
              : 0,
          }))
          .sort((a, b) => b.hasRequest - a.hasRequest);
        updateTableData();
      },
      { deep: true }
    );

    // 监听编辑弹窗关闭
    watch(
      () => state.dialogEditVisible,
      (newVal, oldVal) => {
        if (oldVal && !newVal) {
          getList();
        }
      }
    );
    watch(
      () => state.dialogApprovalVisible,
      (newVal, oldVal) => {
        if (oldVal && !newVal) {
          getList();
        }
      }
    );
    return {
      ...toRefs(state),
      username,
      getList,
      updateTableData,
      handleCurrentChange,
      handleSizeChange,
      searchInfo,
      handleSearch,
      handleFilter,
      handleReset,
      handleCount,
      handleSnapshot,
      handleBackup,
      getBoundRequest,
      hasApprovalRequests,
      handleBound,
      handleApprovalUpdate,
      total,
      //pageData,
      openDialog,
      handleEdit,
      //saveEdit,
      selectedRows,
      handleSelectionChange,
      handleRefresh,
    };
  },
});
</script>

<style scoped>
.layout {
  width: 100%;
  height: 100%;
  background-color: #f5f6f9;
  padding-top: 20px;
}
.main-box {
  width: 98%;
  height: 85vh;
  background-color: #ffffff;
  margin: auto;
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
}
.tit {
  height: 40px;
  line-height: 40px;
  font-weight: 600;
  font-size: 20px;
  text-indent: 1em;
}
.selector-box {
  margin: 10px 20px;
}
.flex-container {
  display: flex;
  flex-flow: row wrap;
  column-gap: 12px;
  align-items: flex-end;
}
.input-wrapper {
  display: flex;
  align-items: center;
  gap: 8px;
}
.btn-list {
  border: 1px solid #e1e3e5;
  border-bottom: none;
  border-radius: 4px 4px 0 0;
  margin: 0 20px;
  padding: 6px 12px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  overflow: hidden;
}
.table-box {
  height: calc(100% - 60px);
  flex: 1;
  margin: 0 20px;
  border: none;
  overflow: auto;
}
.pagination-box {
  transition: margin 0.3s ease;
  margin: 8px 20px 20px;
  height: 32px;
  display: flex;
  align-items: center;
}
</style>
